using BootstrapBlazor.Components;
using COSXML;
using COSXML.Auth;
using COSXML.Model.Object;
using Console = System.Console;

namespace BootstrapBlazorApp.Server.Service;




public class UploadService
{
    private readonly CosXml _cosXml;


     public UploadService() {
        CosXmlConfig config = new CosXmlConfig.Builder()
          .SetRegion("ap-nanjing") // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224 
          .Build();


        string? secretId = "AKID030JXecS7dyCE8pPuqfP0Ri2SuOF0y05";   // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capi
        string secretKey = "Ro5ECCGFbrvrYVLF8D8qZq0xhKm9ViR6"; // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capi
        long durationSecond = 600;          //每次请求签名有效时长，单位为秒
        QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, 
          secretKey, durationSecond);


        _cosXml = new CosXmlServer(config, qCloudCredentialProvider);
      }


      public async Task<string?> TransferUploadBytes(UploadFile file)
      {
        try
        {
          // 存储桶名称，此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer
          string bucket = "sc-1319963658";
          string? cosPath = file.GetFileName(); // 对象键
          byte[]? data = await file.GetBytesAsync();
          
          PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, data);
          // 发起上传
          PutObjectResult result = _cosXml.PutObject(putObjectRequest);
          Console.WriteLine(result.GetResultInfo());
          string? requestUrl = _cosXml.GetObjectUrl(bucket, cosPath);
          return requestUrl;
          
        }
        catch (COSXML.CosException.CosClientException clientEx)
        {
          //请求失败
          Console.WriteLine("CosClientException: " + clientEx);
        }
        catch (COSXML.CosException.CosServerException serverEx)
        {
          //请求失败
          Console.WriteLine("CosServerException: " + serverEx.GetInfo());
        }

        return null;

      }
      
     
}